package com.anpy.bill.interceptor;

import com.anpy.bill.model.result.AccountLoginResult;
import com.anpy.bill.model.result.LoginResult;
import com.anpy.bill.service.TokenService;
import com.anpy.personal.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Token拦截器
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("TokenInterceptor拦截请求: {}", request.getRequestURI());
        
        // 获取token
        String token = extractToken(request);
        
        // 验证token并获取用户信息
        LoginResult user = tokenService.validateTokenAndGetUser(token);
        if (user == null) {
            log.error("无效的token或token已过期");
            CommonResponse.assertError(CommonResponse.LOGIN_ERROR);
            return false;
        }
        
        // 将用户ID存入请求属性，供后续使用
        request.setAttribute("userId", user.getId());
        request.setAttribute("user", user);
        
        // 更新token有效期（可选）
        tokenService.refreshToken(String.valueOf(user.getId()));
        
        return true;
    }
    
    /**
     * 从请求中提取token
     */
    private String extractToken(HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        
        // 如果请求头中没有token，则从请求参数中获取
        if (!StringUtils.hasText(token)) {
            token = request.getParameter("token");
        }
        
        // 如果token为空，抛出异常
        if (!StringUtils.hasText(token)) {
            log.error("请求未携带有效token");
            CommonResponse.assertError(CommonResponse.LOGIN_ERROR);
        }
        
        // 去掉Bearer前缀（如果有）
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        return token;
    }
}
